<template>
  <ElDrawer v-model="opened" :title="formType" direction="rtl" :modal="false">
    <ElSkeleton v-if="loading" animated :rows="10" />
    <ElForm v-else ref="formRef" :model="form" :rules="rules" label-position="right" :disabled="isView" :label-width="80">
      <ElFormItem label="类别名称">
        <ElInput v-model="form.dictName" disabled />
      </ElFormItem>
      <ElFormItem label="类别编码">
        <ElInput v-model="form.type" disabled />
      </ElFormItem>
      <ElFormItem label="标签名" prop="label">
        <ElInput v-model="form.label" placeholder="请输入标签名" />
      </ElFormItem>
      <ElFormItem label="数据值" prop="value">
        <ElInput v-model="form.value" placeholder="请输入数据值" />
      </ElFormItem>
      <ElFormItem label="描述" prop="description">
        <ElInput v-model="form.description" placeholder="请输入描述" />
      </ElFormItem>
      <ElFormItem label="备注信息" prop="remark">
        <ElInput v-model="form.remark" placeholder="请输入备注" />
      </ElFormItem>
      <ElFormItem label="排序">
        <ElInputNumber v-model="form.sortOrder" :min="0" :max="999" controls-position="right" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton v-if="!isView" type="primary" @click="onSaveClicked">保存</ElButton>
      <ElButton v-if="isView" @click="onCancelClicked">关闭</ElButton>
      <ElButton v-else @click="onCancelClicked">取消</ElButton>
    </template>
  </ElDrawer>
</template>
<script setup lang="ts">
import { reactive, ref, unref, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { FormType } from '@/enums'
import { checkItemExist, getDictItem, addDictItem, updateDictItem, getDefault } from '@api/uc/dict'
import { Dict } from '@api/uc/dict/interface'

const formType = ref<FormType>()
const formRef = ref<FormInstance>()
const form = ref<Partial<Dict.ItemForm>>({})
const opened = ref(false)
const loading = ref(true)
const emit = defineEmits(['success'])

// 是否查看
const isView = computed(() => {
  return formType.value === FormType.VIEW
})

// 是否新增
const isAdd = computed(() => {
  return formType.value === FormType.ADD
})

// 权限校验
const validate = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }
  checkItemExist({ id: form.value.id, value: value, dictId: form.value.dictId }).then(resp => {
    if (resp.data) {
      callback(new Error('该字典子项已存在'))
    } else {
      callback()
    }
  })
}

const rules = reactive<FormRules>({
  value: [
    { required: true, message: '请输入数据值', trigger: 'blur' },
    { max: 100, message: '数据值最大长度 100', trigger: 'blur' },
    { validator: validate, trigger: 'blur' }
  ],
  label: [
    { required: true, message: '请输入标签名', trigger: 'blur' },
    { max: 100, message: '标签名最大长度 100', trigger: 'blur' }
  ],
  description: [{ max: 100, message: '描述最大长度 100', trigger: 'blur' }],
  remark: [{ max: 255, message: '备注最大长度 255', trigger: 'blur' }]
})

// 打开表单
async function open(type: FormType, id: string) {
  formType.value = type
  opened.value = true
  if (isAdd.value) {
    try {
      const { data } = await getDefault(id)
      loading.value = false
      form.value = data
    } finally {
      loading.value = false
    }
  } else {
    try {
      const { data } = await getDictItem(id)
      loading.value = false
      form.value = data
    } finally {
      loading.value = false
    }
  }
  formRef.value?.clearValidate()
}

// 关闭表单
function close() {
  loading.value = true
  opened.value = false
}

// 保存按钮
function onSaveClicked() {
  if (!formRef.value) return
  formRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    const params = Object.assign({}, unref(form))
    if (isAdd.value) {
      addDictItem(params).then(() => {
        success()
        sendSuccess()
        close()
      })
    } else {
      updateDictItem(params).then(() => {
        success()
        sendSuccess()
        close()
      })
    }
  })
}

// 成功弹出提示
function success() {
  ElMessage({
    type: 'success',
    message: `成功!`
  })
}

// 取消按钮
function onCancelClicked() {
  close()
}

// 保存成功发送成功事件
function sendSuccess() {
  emit('success')
}

defineExpose({
  open,
  close
})
</script>
<style scoped lang="scss">
:deep(.el-form-item) {
  margin-bottom: 18px !important;
}
</style>
